package com.project.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.bean.UserBean;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    //@Valid表示当前对象的属性需要进行校验，校验信息存放在result对象中
    @RequestMapping("add")
    public String  add(@Valid UserBean user, BindingResult result) throws Exception{
        if(result.hasErrors()){//判断是否有校验失败信息
            //得到校验失败信息集合
            List<FieldError> errorList = result.getFieldErrors();
            ObjectMapper om = new ObjectMapper();
            //将错误信息集合，转化为json字符串
            String errorJson = om.writeValueAsString(errorList);
            return errorJson;
        }
        System.out.println("执行添加操作");
        return "ok";
    }
}
